<template>
  <a-drawer
    :title="title"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="客户名称">
            <Myuser disabled v-model="entity.Object" />
            <!-- <Myuser v-if="this.a == 2" v-model="entity.CustomerName" /> -->

            <!-- <Myuser v-if="this.titie == '编辑样品申请表信息'" v-model="entity.Object" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="组织机构" prop="Department">
            <!-- <a-form-model-item label="选择组织机构" prop="DepartmentId" :labelCol="{ style: 'width: 20%;float:left;' }"> -->
            <a-tree-select
              v-model="entity.DepartmentId"
              allowClear
              :treeData="DepartmentIdTreeData"
              placeholder="请选择组织机构"
              treeDefaultExpandAll
            ></a-tree-select>
            <!-- <a-input v-model="entity.Department" autocomplete="off" placeholder="组织机构" /> -->
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="申请编号号" prop="DocumentNo">
            <a-input disabled v-model="entity.DocumentNo" autocomplete="off" placeholder="系统自动生成" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <!-- <a-col :span="8">
          <a-form-model-item label="销售经理" prop="AccountManager">
            <a-input disabled v-model="entity.AccountManager" autocomplete="off" placeholder="销售经理" />
          </a-form-model-item>
        </a-col> -->

        <a-col :span="8">
          <a-form-model-item label="经办人" prop="Transactor">
            <a-select v-model="entity.Transactor" placeholder="请选择">
              <a-select-option v-for="(item, dei) in List" :key="item.Id" :value="item.Id">
                {{ item.RealName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remark">
            <a-input v-model="entity.Remark" autocomplete="off" placeholder="备注" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="收货地址" prop="DeliverAddress">
            <a-textarea v-model="entity.DeliverAddress" autocomplete="off" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="申请日期">
            <a-date-picker format="YYYY-MM-DD" style="width: 100%" v-model="entity.ApplyDate" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            v-if="title == '查看' || title == '审核' || title == '修改'"
            label="审批意见"
            prop="ApprovalComments"
          >
            <a-input :disabled="title == '查看'" v-model="entity.ApprovalComments" autocomplete="off" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <a-table
      class="tables"
      ref="table"
      :scroll="{ y: 460 }"
      :columns="columns"
      :rowKey="
        (row, index) => {
          return index
        }
      "
      :dataSource="data"
      :pagination="pagination"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :bordered="true"
      size="small"
    >
      <span slot="action" slot-scope="text, record, index">
        <template>
          <a v-if="hasPerm('Quot_PriceListDetails.Delete')" @click="handleDelete([record.Id], index)">删除</a>
        </template>
      </span>
      <!-- 辅助数量 -->
      <template slot="AuxiliaryQuantity" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.AuxiliaryQuantity"></a-input>
      </template>
      <!-- 主数量 -->
      <template slot="MainQuantity" slot-scope="text, record">
        <a-input
          style="text-align: right;"
          type="number"
          size="small"
          class="input"
          v-model="record.MainQuantity"
        ></a-input>
      </template>
      <!-- 批次 -->
      <template slot="Batch" slot-scope="text, record">
        <a-input size="small" class="input" type="number" v-model="record.Batch"></a-input>
      </template>
      <!-- 备注 -->
      <template slot="Remark" slot-scope="text, record">
        <a-input size="small" class="input" v-model="record.Remark"></a-input>
      </template>
    </a-table>
    <MaterialChoose ref="materialChoose" @onChoose="handleChoose"></MaterialChoose>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button type="primary" @click="addTable">添加</a-button>&nbsp; <a-button @click="close">取消</a-button>&nbsp;
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import MaterialChoose from '@/components/MaterialChoose/MaterialChooseCopy1.vue'
import Myuser from '@/components/Myuser/List.vue'
import moment from 'moment'

const columns = [
  { title: '产品名称', dataIndex: 'cInvName' },
  // {
  //   title: '辅助数量',
  //   dataIndex: 'AuxiliaryQuantity',
  //   align: 'center',
  //   scopedSlots: { customRender: 'AuxiliaryQuantity' }
  // },
  { title: '数量', dataIndex: 'MainQuantity', align: 'right', scopedSlots: { customRender: 'MainQuantity' } },
  // { title: '批次', dataIndex: 'Batch', scopedSlots: { customRender: 'Batch' } },
  { title: '备注', dataIndex: 'Remark', scopedSlots: { customRender: 'Remark' } },

  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' } }
]
export default {
  watch: {
    data: {
      handler(n, o) {
        //console.log(n)
        n.forEach(item => {
          if (Number(item.MainQuantity) < 0) {
            this.$set(item, 'MainQuantity', 1)
            this.$message.warning('数量不能小于0')
            return
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  props: {
    parentObj: Object
  },
  components: {
    Myuser,
    MaterialChoose
  },

  data() {
    return {
      columns,
      List: [],
      data: [],
      selectedRowKeys: [],
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      id: '',
      cCusName: '',
      a: 1,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      DepartmentIdTreeData: [],
      filters: {},
      sorter: { field: 'Id', order: 'desc' },
      visible: false,
      loading: false,
      entity: { objects: {} },
      rules: {
        CustomerName: [{ required: true, message: '未输入', trigger: 'change' }],
        // Department: [{ required: true, message: '未输入', trigger: 'change' }],
        AccountManager: [{ required: true, message: '未输入', trigger: 'blur' }],
        Transactor: [{ required: true, message: '未输入', trigger: 'blur' }],
        DeliverAddress: [{ required: true, message: '未输入', trigger: 'blur' }]
      },
      title: ''
    }
  },
  methods: {
    Myuser() {
      //console.log(123)
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleDelete(ids, index) {
      if (ids[0]) {
        var thisObj = this
        this.$confirm({
          title: '确认删除吗?',
          onOk() {
            return new Promise((resolve, reject) => {
              thisObj.$http.post('/SampleManagement/SPL_SampleApplyDetails/DeleteData', ids).then(resJson => {
                resolve()

                if (resJson.Success) {
                  thisObj.$message.success('操作成功!')

                  thisObj.getDataList()
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
              })
            })
          }
        })
      } else {
        this.data.splice(index, 1)
        //console.log(123)
      }
    },
    // 反填
    getDataList() {
      this.$http
        .post('/SampleManagement/SPL_SampleApplyMain/GetTheDataOfAll', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Id',
          SortType: 'desc',
          Search: {
            Condition: 'Id',
            Keyword: this.Id
          }
        })
        .then(res => {
          //console.log(res)
          if (res.Success) {
            this.entity = res.Data
            //console.log(res.Data)
            this.$set(
              this.entity,
              'Object',
              res.Data.CustomerName
              // Id: res.Data.CustomerId ? res.Data.CustomerId : '123',
              // cCusName: res.Data.CustomerName
            )

            if (this.entity['CreateTime']) {
              this.entity['CreateTime'] = moment(this.entity['CreateTime'])
            }
            this.data = res.Data.SSAD_List
            //console.log(this.data)
            if (res.Data.Total) {
              const pagination = { ...this.pagination }
              pagination.total = res.Data.Total
              this.pagination = pagination
            }
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      
      // this.getDataList()
    },
    addTable() {
      //console.log(12113)
      this.$refs.materialChoose.openChoose(null, this.data)
    },
    init() {
      this.visible = true
      this.data = []
      this.entity = {
        objects: {}
      }
      this.entity.ApplyDate = moment(new Date())
      this.$http.post('/Base_Manage/Base_Department/GetTreeDataList', {}).then(resJson => {
        if (resJson.Success) {
          this.DepartmentIdTreeData = resJson.Data
        }
      })
      this.$http.post('/Base_Manage/Base_User/GetDataList', {}).then(resJson => {
        this.loading = false
        this.List = resJson.Data
      })
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    openForm(item, title) {
      this.init()
      this.title = title

      console.log(item)
      if (item.cCusName) this.$set(this.entity, 'Object', item.cCusName)
      if (item.cCusCode) this.$set(this.entity, 'Obe', item.Id || item.cCusCode)
      this.$set(this.entity, 'AccountManager', item.AllocationName)
      //console.log(this.entity.Object)
      this.cCusName = item.cCusName
      this.id = item.cCusCode
    },

    close() {
      this.visible = false

      this.entity = {}
    },
    handleChoose(a) {
      //console.log(a)

      //console.log(this.data)
      var ar = []

      this.data.forEach(item => {
        //console.log(this.data)
        a.forEach((val, i) => {
          //console.log(val)
          if (item.ProductId == val.Id) {
            ar.push(val)
            delete a[i]
          }
        })
      })
      //console.log(ar)

      if (ar.length == 0) {
        a.forEach(item => {
          //console.log(this.data)

          this.data.push({
            ProductId: item.cInvCode,
            cInvName: item.cInvName
          })
        })
        //console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        this.$message.error('重复产品已筛选掉')
        a.forEach(item => {
          //console.log(item)
          this.data = [...this.data, item]
        })

        //console.log(a)
      }
    },
    handleSubmit() {
      //console.log(this.entity)

      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }
        this.loading = true
        if (this.title == '客户样品') {
          //console.log(this.entity.Object)
          this.entity.CustomerName = this.entity.Object
          this.entity.CustomerId = this.entity.Obe
          //console.log(this.entity.CustomerName)
        } else {
          //console.log(this.entity.Object)
        }
        if (this.title == '编辑样品申请表信息' && this.entity.Object.Id) {
          this.entity.CustomerName = this.entity.Object.cCusName
          this.entity.CustomerId = this.entity.Object.Id
        }
        // if (this.cCusName) entityData.CustomerName = this.cCusName
        // if (this.id) entityData.CustomerId = this.id
        var entityData = { ...this.entity }
        var SSAD_List = [...this.data]
        this.SSAD_List = SSAD_List
        //console.log(this.SSAD_List)
        entityData.SSAD_List = this.SSAD_List
        this.$http.post('/SampleManagement/SPL_SampleApplyMain/SaveData', entityData).then(resJson => {
          this.loading = false

          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false
            if (this.parentObj.user == 1) {
              this.parentObj.getDataList()
            } else {
              this.parentObj.getuserList()
            }
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    }
  }
}
</script>
